package Com.Ring.TradingMobile;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.ksoap2.HeaderProperty;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import Com.Ring.TradingMobile.Lib.Common;
import Com.Ring.TradingMobile.Lib.RET_CODE;
import Com.Ring.TradingMobile.Lib.Session;
import Com.Ring.TradingMobile.Object.Advances;
import Com.Ring.TradingMobile.Service.WebService;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;

public class UngTruocActivity extends Activity{

	private Button btn_AdvanceStatus;
	private TextView lblAvaibilityContent;
	private Button btn_Buy;
	private Button btn_Sell;
	@SuppressWarnings("unused")
	private Button btn_Submit;
	private Button btn_Back;
	private Button btn_Home;
	private TableLayout tabAdvances;
	@SuppressWarnings("unused")
	private TableLayout tabDetailAdvances;
	private TextView lblAccountTextView;
	
	private Handler handler;
	
	private String TAG = "UngTruocActivity";
	
	@SuppressWarnings("unused")
	private Runnable runable;
	@SuppressWarnings("unused")
	private int[] StrHeaderId = new int[] { R.string.strMaCK,
			R.string.str_Total, R.string.str_MoneyAvailability,
			R.string.str_T1, R.string.str_T2, R.string.str_T3,
			R.string.str_PriceAvg, R.string.str_PriceMarket,
			R.string.str_GrainLoss };
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ungtruoc);
		InitControlId();
		List<Advances> listAdvances = GetAdvances(Session.subCustAccounts.get(0));
		SetAdvancesView(listAdvances);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	private void InitControlId() {
		btn_Back = (Button) findViewById(R.id.btnBack);
		btn_Buy = (Button) findViewById(R.id.btn_Mua);
		btn_Submit = (Button) findViewById(R.id.btn_Submit);
		btn_Home = (Button) findViewById(R.id.btnHome);
		btn_Sell = (Button) findViewById(R.id.btn_Ban);
		lblAvaibilityContent = (TextView)findViewById(R.id.lblAvailabilityContent);
		lblAccountTextView = (TextView) findViewById(R.id.lblTaiKhoan);
		lblAccountTextView.setText("TK: " + Session.subCustAccounts.get(0));
		tabAdvances = (TableLayout)findViewById(R.id.tableAdvances);
		tabDetailAdvances = (TableLayout)findViewById(R.id.tableDetailAdvances);

		handler = new Handler();
		InitControlListen();
		CreateHeaderAdvances();
	}
	
	private void InitControlListen() {
		btn_Back.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
		btn_Home.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(),
						TradingMobileLoggedActivity.class);
				startActivity(intent);
				finish();
			}
		});
		btn_Buy.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(),
						MuaActivity.class);
				startActivity(intent);
				finish();
			}
		});
		btn_Sell.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(),
						BanActivity.class);
				startActivity(intent);
				finish();
			}
		});
		btn_AdvanceStatus.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(),
						TrangThaiLenhUngActivity.class);
				startActivity(intent);
				finish();
			}
		});
	}
	
	private void CreateHeaderAdvances() {
		tabAdvances.removeAllViews();
		TableRow trRowHeader = new TableRow(this);
		TextView tdDateSell = new TextView(this);
		TextView tdBorrowed = new TextView(this);
		trRowHeader.setLayoutParams(new LayoutParams(android.widget.TableRow.LayoutParams.FILL_PARENT, android.widget.TableRow.LayoutParams.WRAP_CONTENT));
		tdDateSell.setLayoutParams(new LayoutParams(android.widget.TableLayout.LayoutParams.FILL_PARENT, android.widget.TableLayout.LayoutParams.WRAP_CONTENT));
		tdBorrowed.setLayoutParams(new LayoutParams(android.widget.TableLayout.LayoutParams.FILL_PARENT, android.widget.TableLayout.LayoutParams.WRAP_CONTENT));
		tdDateSell.setText(R.string.str_DaySell);
		tdBorrowed.setText(R.string.str_borrowed);
		tdDateSell.setPadding(5, 5, 5, 5);
		tdBorrowed.setPadding(5, 5, 5, 5);
		trRowHeader.addView(tdDateSell);
		trRowHeader.addView(tdBorrowed);
		tabAdvances.addView(trRowHeader,new LayoutParams(android.widget.TableRow.LayoutParams.FILL_PARENT, android.widget.TableRow.LayoutParams.WRAP_CONTENT));
	}
	
	@SuppressWarnings("unused")
	private void LoadAdvances() {
		runable = new Runnable() {
			public void run() {
				handler.post(new Runnable() {
					public void run() {
						List<Advances> listAdvances = GetAdvances(Session.subCustAccounts.get(0));
						SetAdvancesView(listAdvances);
					}
				});
			}
		};
	}
	
	private void SetAdvancesView(List<Advances> listAdvances) {
		if (listAdvances!=null && listAdvances.size()>0) {
			CreateHeaderAdvances();
			int id=0;
			for (Advances advances : listAdvances) {
				RelativeLayout relativeLayout = new RelativeLayout(UngTruocActivity.this);
				Button btnAdvances = new Button(UngTruocActivity.this);
				TextView tradeDateView = new TextView(UngTruocActivity.this);
				TextView canMaxAdvancesView = new TextView(UngTruocActivity.this);
				
				btnAdvances.setId(id+1000);
				tradeDateView.setId(id+2000);
				canMaxAdvancesView.setId(id+3000);
				
				tradeDateView.setText(advances.TradeDate);
				canMaxAdvancesView.setText(advances.MaxCanAdvance);
				btnAdvances.setText(R.string.str_SendAdvance);
				
				tabAdvances.addView(relativeLayout);
				relativeLayout.addView(tradeDateView);
				relativeLayout.addView(canMaxAdvancesView);
				relativeLayout.addView(btnAdvances);
				
				RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
				params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
				params.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
				tradeDateView.setLayoutParams(params);
				tradeDateView.setPadding(10, 0, 0, 0);
				params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
				params.addRule(RelativeLayout.RIGHT_OF, tradeDateView.getId());
				params.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
				canMaxAdvancesView.setLayoutParams(params);
				canMaxAdvancesView.setPadding(10, 0, 0, 0);
				params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
				params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
				params.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
				btnAdvances.setLayoutParams(params);
				btnAdvances.setPadding(0, 0, 10, 0);
				
				id++;
			}
			
		}
	}
	
	
	
	private List<Advances> GetAdvances(String subAccount) {
		List<Advances> listData = new ArrayList<Advances>();
		@SuppressWarnings("unused")
		int accountType = Common.ACCOUNT.GetAccountType(subAccount);
		SoapObject request = new SoapObject(WebService.NAMESPACE,
				WebService.GetAdvanceInfo);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		
		PropertyInfo parAccountNo = new PropertyInfo();
		parAccountNo.setName("accountNo");
		parAccountNo.setValue(subAccount);
		parAccountNo.setNamespace(WebService.NAMESPACE);
		
		request.addProperty(parAccountNo);

		envelope.setOutputSoapObject(request);
		HttpTransportSE http = new HttpTransportSE(WebService.ADDRESS_ETRADE_SERVICE);
		String soapAction = WebService.NAMESPACE + WebService.GetAdvanceInfo;

		try {
			LinkedList<HeaderProperty> getSession = Session.GetSession();
			@SuppressWarnings("unchecked")
			List<HeaderProperty> respHeaders = http.call(soapAction, envelope, getSession);
			if (respHeaders != null) {
				Session.SetSession(respHeaders);
			} else
				return listData;
			JSONObject resultsObj = new JSONObject(envelope.getResponse()
					.toString());
			int retCode;
			if (resultsObj != null) {
				retCode = resultsObj.getInt("RetCode");
				if (retCode == RET_CODE.SUCCESS.Value) {
					String avaibilityContent = resultsObj.getJSONObject("Result").getJSONObject("SumInPage").getString("MaxCanAdvance");
					lblAvaibilityContent.setText(avaibilityContent);
					JSONArray dataAdvances = resultsObj
							.getJSONObject("Result").getJSONArray("Data");
					for (int i = 0; i < dataAdvances.length(); i++) {
						JSONObject jsonObject = dataAdvances.getJSONObject(i);
						Advances advances = new Advances();
						advances.TradeDate = Common.ConvertToDateStrVi(jsonObject.getString(Advances.PropertyString.TradeDate.toString()));
						advances.DueDate =  Common.ConvertToDateStrVi(jsonObject.getString(Advances.PropertyString.DueDate.toString()));
						advances.DueDateInit = Common.ConvertToDateStrInit(jsonObject.getString(Advances.PropertyString.DueDate.toString()));
						advances.TradeDateInit = Common.ConvertToDateStrInit(jsonObject.getString(Advances.PropertyString.TradeDate.toString()));
						advances.SellAmt = Common.FormatNumber(jsonObject.getDouble(Advances.PropertyString.SellAmt.toString()));
						advances.SellAmtInit = jsonObject.getDouble(Advances.PropertyString.SellAmt.toString());
						advances.AdvanceFinished = Common.FormatNumber(jsonObject.getDouble(Advances.PropertyString.AdvanceFinished.toString()));
	                    advances.MaxCanAdvance = Common.FormatNumber(jsonObject.getDouble(Advances.PropertyString.MaxCanAdvance.toString()));
	                    advances.MaxCanAdvanceInit = jsonObject.getDouble(Advances.PropertyString.MaxCanAdvance.toString());
	                    advances.CanAdvance = jsonObject.getBoolean(Advances.PropertyString.CanAdvance.toString());
	                    advances.CalDate = jsonObject.getInt(Advances.PropertyString.NDay.toString());
						listData.add(advances);
					}
				}
			}
		} catch (Exception ex) {
			Log.d(TAG, ex.toString());
		}
		return listData;
	}
	
}
